<template>
  <el-dialog :model-value="visible" :title="title" width="800px" :before-close="handleClose" append-to-body>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="right">
      <!-- 第一行：属性类型、属性名称、属性标识 -->
      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item label="属性名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入属性名称" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="属性类型" prop="propertyType">
            <el-select v-model="formData.propertyType" placeholder="请选择属性类型" style="width: 100%">
              <el-option value="0" label="运行参数" />
              <el-option value="1" label="健康参数" />
              <el-option value="2" label="辅助参数" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <!-- 第二行：属性编号、数据类型 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="属性编号" prop="number">
            <el-input-number
              v-model="formData.number"
              placeholder="请输入属性编号"
              style="width: 100%"
              :min="1"
              :max="999"
              :step="1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="属性标识" prop="identifier">
            <el-input v-model="formData.identifier" placeholder="请输入属性标识" maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 取值范围输入框 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数据类型" prop="dataType">
            <el-select v-model="formData.dataType" placeholder="请选择数据类型" style="width: 100%">
              <el-option value="fixed" label="fixed固定值" />
              <el-option value="bool" label="bool布尔型" />
              <el-option value="int32" label="int32整型" />
              <el-option value="float" label="float浮点数" />
              <el-option value="double" label="double双精度浮点数" />
              <el-option value="text" label="text文本" />
              <el-option value="enum" label="enum枚举" />
              <el-option value="json" label="json对象" />
              <el-option value="array" label="array数组" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 取值范围输入框 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="取值范围" prop="valueRange">
            <el-input v-model="formData.valueRange" placeholder="请输入取值范围" maxlength="200" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：默认值 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="默认值" prop="defaultValue">
            <el-input v-model="formData.defaultValue" placeholder="请输入内容" maxlength="200" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：属性单位、UI图链接 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="属性单位" prop="unit">
            <el-input v-model="formData.unit" placeholder="请输入属性单位" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="UI图链接" prop="uiLink">
            <el-input v-model="formData.uiLink" placeholder="请输入UI图链接" maxlength="200" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行：备注 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" maxlength="500" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行：是否必选 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="是否必选" prop="required">
            <el-radio-group v-model="formData.required">
              <el-radio :label="2">是否必选</el-radio>
              <el-radio :label="0">非必选</el-radio>
              <el-radio :label="1">必选</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行：读写方式 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="读写方式" prop="readWriteMode">
            <el-radio-group v-model="formData.readWriteMode">
              <el-radio label="readwrite">读写</el-radio>
              <el-radio label="readonly">只读</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { ConfigAttributeInfo, ConfigAttributeFormData } from '@/api/IOT/protocolManage/configAttributeManage/types'

// Props定义
interface Props {
  visible: boolean
  title?: string
  data?: ConfigAttributeInfo
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  title: '新增配置属性',
  loading: false
})

// Emits定义
interface Emits {
  'update:visible': [value: boolean]
  'submit': [data: ConfigAttributeFormData]
  'cancel': []
}

const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref<FormInstance>()
const formData = ref<ConfigAttributeFormData>({
  dataformatId: '',
  propertyType: '0',
  name: '',
  identifier: '',
  number: '',
  required: 0,
  dataType: 'fixed',
  valueRange: '',
  defaultValue: '',
  unit: '',
  uiLink: '',
  remark: '',
  readWriteMode: 'readwrite',
  status: 1,
  protocolVersionId: ''
})

// 表单验证规则
const rules: FormRules = {
  propertyType: [
    { required: true, message: '请选择属性类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入属性名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  identifier: [
    { required: true, message: '请输入属性标识', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '标识必须以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请选择属性编号', trigger: 'change' }
  ],
  dataType: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ],
  valueRange: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  defaultValue: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  unit: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ],
  uiLink: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ],
  required: [
    { required: true, message: '请选择是否必选', trigger: 'change' }
  ],
  readWriteMode: [
    { required: true, message: '请选择读写方式', trigger: 'change' }
  ]
}

// 计算属性
const isEdit = computed(() => !!props.data?.id)

// 工具函数 - 重置表单
const resetForm = () => {
  Object.assign(formData.value, {
    dataformatId: '',
    propertyType: 0,
    name: '',
    identifier: '',
    number: '',
    required: 0,
    dataType: 'fixed',
    valueRange: '',
    defaultValue: '',
    unit: '',
    uiLink: '',
    remark: '',
    readWriteMode: 'readwrite',
    status: 1,
    protocolVersionId: ''
  })
  formRef.value?.clearValidate()
}



// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (props.data) {
      // 编辑模式，填充数据
      Object.assign(formData.value, {
        dataformatId: props.data.dataformatId || '',
        propertyType: props.data.propertyType || 0,
        name: props.data.name || '',
        identifier: props.data.identifier || '',
        number: props.data.number || '',
        required: props.data.required || 0,
        dataType: props.data.dataType || 'fixed',
        valueRange: props.data.valueRange || '',
        defaultValue: props.data.defaultValue || '',
        unit: props.data.unit || '',
        uiLink: props.data.uiLink || '',
        remark: props.data.remark || '',
        readWriteMode: props.data.readWriteMode || 'readwrite',
        status: props.data.status || 1,
        protocolVersionId: props.data.protocolVersionId || ''
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
})

// 监听数据变化
watch(() => props.data, (newData) => {
  if (newData && props.visible) {
    Object.assign(formData.value, {
      dataformatId: newData.dataformatId || '',
      propertyType: newData.propertyType || 0,
      name: newData.name || '',
      identifier: newData.identifier || '',
      number: newData.number || '',
      required: newData.required || 0,
      dataType: newData.dataType || 'fixed',
      valueRange: newData.valueRange || '',
      defaultValue: newData.defaultValue || '',
      unit: newData.unit || '',
      uiLink: newData.uiLink || '',
      remark: newData.remark || '',
      readWriteMode: newData.readWriteMode || 'readwrite',
      status: newData.status || 1,
      protocolVersionId: newData.protocolVersionId || ''
    })
  }
}, { deep: true })

// 事件处理函数
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('submit', { ...formData.value })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  resetForm()
  emit('cancel')
  emit('update:visible', false)
}

const handleClose = () => {
  handleCancel()
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.enum-values {
  width: 100%;
}

.enum-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.enum-item:last-child {
  margin-bottom: 0;
}
</style>